import { defineStore } from 'pinia'
// import {getCurrentInstance,type ComponentInternalInstance} from 'vue';
import router from '@/router';

import {user_login} from "@/api/User/index";
import { useRequest, invalidateCache } from 'alova';
import { MylocalStorage } from '@/config/storage/MylocalStorage'; // 确保路径正确
 

export const userLoginStore = defineStore('login', {
  state: () => {
    return {
      User:{
        username:undefined,
        password:undefined
      },
      token:""
    }
  },
 
  getters: {
	  getUser(){

    }
  },
  actions: {
   LOGIN(){

    
    
    // 获取proxy属性 可以访问挂载在全局的实例和方法(需要断言 否则ts报错)
    // const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const {onSuccess,onError} = useRequest(user_login(this.User));
      onSuccess(todoListRaw => {
        const {code,message,token,data}=todoListRaw.data;
        if(code===200 || message==="登录成功"){
          // proxy?.$globaMylocalStorage.setItem("token",token);
          MylocalStorage.setItem("token",token).then(res=>{
            router.push("/");
            this.token=token;
          
            // 在这里处理登录逻辑，比如调用API  
            console.log('登录:', this.User);
          })

        
        }else{
          alert(todoListRaw.data.message);
        }
      })
      // user_login(user).then(res=>{
      //   console.log(res);
      //   const {code,message,token}=res.data;
      //   if(code===200 || message==="登录成功"){
      //     proxy?.$globaMylocalStorage.setItem("token",token);
          
      //     router.push({name:"index"});
  
          
      //     // 在这里处理登录逻辑，比如调用API  
      //     console.log('登录:', user);
      //   }
      // })
   }
  },
  persist: {
    storage: sessionStorage,
    key: 'login-store',

    pick: ['token'],
  },
})
